﻿// #define TRACE

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Diagnostics;


namespace Hockey.UILayer.Controls
{

    /// <summary>
    /// Layout Panel arranging control as a square in the center
    /// TO-DO: make internal
    /// </summary>
    public class SquarePanel: Panel
    {       
        protected override Size MeasureOverride(Size availableSize)        
        {
            if (Children.Count == 0)
                return availableSize;

            UIElement visual = this.GetVisualChild(0) as UIElement;
            if (visual != null)
            {
                double minSize = Math.Min(availableSize.Width, availableSize.Height);
                availableSize.Width = minSize;
                availableSize.Height = minSize;
                visual.Measure(availableSize);
            }

        #if TRACE
            Trace.TraceInformation("SquarePanel Width:{0}, Height: {1}", availableSize.Width, availableSize.Height);
        #endif

            return availableSize;
        }

        /// <summary>
        /// Arranging method
        /// </summary>
        protected override Size ArrangeOverride(Size finalSize)
        {
            if (Children.Count == 0)
                return finalSize;

            UIElement visual = this.GetVisualChild(0) as UIElement;
            if (visual != null)
            {
                // do square centering
                double size = Math.Min(finalSize.Width, finalSize.Height);
                double x = (finalSize.Width - size) / 2;
                double y = (finalSize.Height - size) / 2;

            #if TRACE
                Trace.TraceInformation("SquarePanel Rect, X: {0}, Y: {1}, Size: {2}", x, y, size);
            #endif

                // do arranging
                visual.Arrange(new Rect(x, y, size, size));             
            }

            return finalSize;
        }
    }
}
